//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using CommunityServer.Components;

namespace CommunityServer.Controls
{
	/// <summary>
	/// Allows a member to change his username.
	/// </summary>
	public class ChangeUserName : SecureTemplatedWebControl
	{
		CSContext csContext = CSContext.Current;
		User user = null;
		bool isModal = false;

		protected StatusMessage message;
		protected IText currentUserName;
		protected TextBox desiredUserName;
		protected CheckBox ignoreDisallowedNames;
		protected IButton changeUserNameButton;

		public ChangeUserName() : base()
		{
			// do we have a target user?
			if (csContext.UserID <= 0)
				return;

			// do we have rights to change username?
			if (csContext.User.IsAdministrator || csContext.User.IsMembershipAdministrator)
				user = Users.GetUser(csContext.UserID, false);
		}

		protected override void AttachChildControls()
		{
			// we need a valid user
			if (user == null)
				return;

			// attach message control
			message = FindControl("StatusMessage") as StatusMessage;

			// attach existing username control; prepopulate
			currentUserName = FindText("CurrentUserName");
			if (currentUserName != null)
				currentUserName.Text = user.Username;

			// attach new username control
			desiredUserName = FindControl("DesiredUserName") as TextBox;

			// attach ignore control; configure
			ignoreDisallowedNames = FindControl("IgnoreDisallowedNames") as CheckBox;
			if (ignoreDisallowedNames != null)
				ignoreDisallowedNames.Text = ResourceManager.GetString("ChangeUserName_IgnoreDisallowedNames");

			// attach button; configure; wire-up events
			changeUserNameButton = FindButton("ChangeUserNameButton");
			if (changeUserNameButton != null)
			{
				changeUserNameButton.Text = ResourceManager.GetString("ChangeUserName_Button");
				changeUserNameButton.Visible = true;
				changeUserNameButton.Click += new EventHandler(ChangeUserName_Click);
			}
		}

		protected void ChangeUserName_Click(Object sender, EventArgs e)
		{
			// only continue if all page-level validation succeeded
			if (!Page.IsValid)
				return;

			// only continue if we've got a valid user
			if (user == null)
				return;

			// assume failure
			RenameUserStatus status = RenameUserStatus.UnknownFailure;

			// get desired username
			string newUserName = string.Empty;
			if (desiredUserName != null)
				newUserName = desiredUserName.Text.Trim();

			// should we check username against blacklist
			bool ignore = false;
			if (ignoreDisallowedNames != null)
				ignore = ignoreDisallowedNames.Checked;

			// is desired username the correct length?
			if ((newUserName.Length >= csContext.SiteSettings.UsernameMinLength)
				&& (newUserName.Length <= csContext.SiteSettings.UsernameMaxLength))
			{
				// if desired username matches regex criteria, attempt rename
				Regex regex = new Regex(csContext.SiteSettings.UsernameRegex);
				if (regex.Matches(newUserName).Count > 0)
					status = Users.RenameUser(user, newUserName, ignore);
			}

			// did we succeed?
			if (status == RenameUserStatus.Success)
			{
				// close modal
				if (isModal)
				{
					Modal.ClosePage(this.Page);
					return;
				}

				// where do we go next
				string returnUrl = csContext.ReturnUrl;
				if(Globals.IsNullorEmpty(returnUrl))
					returnUrl = Globals.GetSiteUrls().CleanUserEditProfile;

				LeaveSecureConnection(returnUrl);
				return;
			}

			// rename didn't work; display error
			if (message != null)
			{
				message.Visible = true;
				message.Success = (status == RenameUserStatus.Success);
				message.ResourceName = LookupResourceForStatus(status);
			}
		}

		public bool IsModal
		{
			get { return isModal; }
			set { isModal = value; }
		}

		private string LookupResourceForStatus(RenameUserStatus status)
		{
			switch (status)
			{
				case RenameUserStatus.Success:
					return "ChangeUserName_Success";
				case RenameUserStatus.DisallowedUserName:
					return "ChangeUserName_DisallowedUserName";
				case RenameUserStatus.DuplicateUserName:
					return "ChangeUserName_DuplicateUserName";
				case RenameUserStatus.UnknownFailure:
				default:
					return "ChangeUserName_UnknownFailure";
			}
		}
	}
}
